<?php 
/**
* @author Oliver Leisalu, Inditel Meedia OÜ
* @package DomLogger
*/
class DomDBLogger {
	
	protected $prefix = 'log_';
	protected $connectionAlias;
	protected $name;
	
	/**
	* @throws RuntimeException 100 - not connected to database, 101 - invalid log name.
	*/
	public function __construct( $name, $connectionAlias = DomSql::DEFAULT_ALIAS ) {
		
		if( !preg_match('/^[A-Za-z0-9_-]+$/', $name) )
			throw new RuntimeException('Invalid log name "'.$name.'", log name must match ^[A-Za-z0-9_-]+$', 101);
		
		$this->name = $name;	
		$this->connectionAlias = $connectionAlias;
		
		if( DomSql::connected( $this->connectionAlias ) === false ) {
			throw new RuntimeException('DomDBLogger can\'t log event. DomSql is not connected to database!', 100);
		}
	}
	
	public function getTableName() {
		return strtolower($this->prefix.$this->name);
	}
	
	public function read( $entries = 10 ) {
		return DomSql::selectQuery('SELECT id, time, ip, message FROM '.$this->getTableName().' ORDER BY time DESC LIMIT '.(int)$entries.'');
	}
	
	public function flush() {
		
	}
	
	/**
	* @param String $message
	* @return Int Last insert id.
	*/
	public function log( $title, $message = '', $code = 0 ) {

		$query = 'INSERT INTO '.$this->getTableName().' (ip,time,code,title,message) values (\''.ip().'\',NOW(),'.(int)$code.',\''.addslashes($title).'\',\''.addslashes($message).'\')';
			
		try {

			DomSql::query( $query, $this->connectionAlias );

		} catch( Exception $e ) {
			if( $e->getCode() == 1146 ) {
				$this->createTable();
				DomSql::query( $query, $this->connectionAlias );
			} else {
				throw $e;
			}
		}
		return DomSql::lastInsertId();
		
	}
	
	private function createTable() {
		DomSql::query('
				CREATE TABLE IF NOT EXISTS '.$this->getTableName().' (
					id int(11) PRIMARY KEY auto_increment,
					ip varchar(15),
					time datetime,
					code int(11),
					title longtext,
					message longtext,
					index(ip),
					index(code),
					index(time)
				) ENGINE=MyIsam CHARACTER SET utf8 COLLATE utf8_estonian_ci');
	}
}
?>